import React from 'react';
import PropTypes from 'prop-types';
import { Dialog, Form, Input, Field, Button, Message } from '@teamix/ui';
import exceed from 'utils/apimap';
import './index.scss';
import intl from '../../../../../../../../../locale';

const FormItem = Form.Item;
const formItemLayout = {
  labelCol: {
    span: 6,
  },

  wrapperCol: {
    span: 14,
  },
};

export default class AliasNameDialog extends React.Component {
  static propTypes = {
    closeModal: PropTypes.func,
    trigger: PropTypes.element,
    path: PropTypes.string,
  };

  static defaultProps = {
    closeModal: () => {},
    trigger: PropTypes.element,
    path: '',
  };

  constructor(props) {
    super(props);
    this.field = new Field(this);
    this.state = {
      submitting: false,
    };
  }

  static getDerivedStateFromProps(props) {
    if (props.trigger) {
      return {};
    }
    return {
      isModalOpen: props.isModalOpen,
    };
  }

  onClose = () => {
    this.setState({
      isModalOpen: false,
    });

    this.props.closeModal();
  };

  handleOk = () => {
    if (this.state.submitting) {
      return;
    }
    this.field.validate((errors) => {
      if (!errors) {
        this.setState({ submitting: true });
        const formData = this.field.getValues();
        this.setOrgAliasName(formData, (type) => {
          if (type === 'isFail') {
            this.field.reset();
          }
          this.setState({ submitting: false });
          this.onClose();
        });
      }
    });
  };

  setOrgAliasName = (formData, cb) => {
    const { id } = window.FORCE.organization;
    exceed
      .fetch({
        api: 'organization.alias.name.update',
        params: {
          id,
        },

        data: formData,
      })
      .then((result) => {
        Message.success({
          title: intl.get({
            id: 'code-assets.customize.containers.aliasNameDialog.TheIdentifierIsSet',
            defaultMessage: '标识名设置成功',
          }),
        });

        window.location.reload();
        cb && cb(result);
      })
      .fail(() => {
        cb && cb('isFail');
      });
  };

  showModal = () => {
    this.setState({
      isModalOpen: true,
    });
  };

  pathValidator = (rule, value, callback) => {
    const { path } = this.props;
    if (!value) {
      callback();
      return;
    }
    if (path !== value) {
      callback(
        intl.get({
          id: 'code-assets.customize.containers.aliasNameDialog.TheErrorMessageReturnedBecause',
          defaultMessage: '企业标识名输入错误，请重新输入',
        }),
      );
    } else {
      callback();
    }
  };

  render() {
    const { init } = this.field;
    const { path } = this.props;
    const isConfirmBtndisabled = !this.field.getValue('path') || this.field.getError('path');

    return (
      <React.Fragment>
        {this.state.isModalOpen ? (
          <Dialog
            className="delete-path-resource"
            title={intl.get({
              id: 'code-assets.customize.containers.aliasNameDialog.SaveEnterpriseIdentificationName',
              defaultMessage: '保存企业标识名',
            })}
            visible
            style={{ width: '440px' }}
            onClose={this.onClose}
            footer={
              <Button
                type="primary"
                style={{ width: '100%' }}
                onClick={this.handleOk}
                loading={!!this.state.submitting}
                disabled={!!isConfirmBtndisabled}
              >
                {intl.get({
                  id: 'code-assets.customize.containers.aliasNameDialog.Confirmation',
                  defaultMessage: '确认',
                })}
              </Button>
            }
          >
            <div style={{ marginBottom: '10px' }}>
              <Message
                title={intl.get({
                  id: 'code-assets.customize.containers.aliasNameDialog.TheEnterpriseIdentificationNameCannot',
                  defaultMessage: '一旦设定企业标识名，不可更改',
                })}
                key="warning"
                type="warning"
                shape="inline"
              />
            </div>
            <Form {...formItemLayout} field={this.field} labelAlign="top">
              <FormItem
                label={intl.get(
                  {
                    id: 'code-assets.customize.containers.aliasNameDialog.EnterTheEnterpriseIdentificationName',
                    defaultMessage: '请输入企业标识名 {path} 以确认保存',
                  },
                  { path },
                )}
                required
              >
                <Input
                  autoFocus
                  {...init('path', {
                    rules: [
                      {
                        required: true,
                        message: intl.get({
                          id: 'code-assets.src.utils.locale.ThisParameterIsRequired',
                          defaultMessage: '该项为必填项',
                        }),
                      },

                      {
                        validator: this.pathValidator,
                      },
                    ],
                  })}
                />
              </FormItem>
            </Form>
          </Dialog>
        ) : null}
        {!!this.props.trigger &&
          React.cloneElement(this.props.trigger, {
            onClick: (e) => {
              this.props.trigger.props.onClick && this.props.trigger.props.onClick(e);
              this.showModal();
            },
          })}
      </React.Fragment>
    );
  }
}
